import frappe
import requests
from frappe import _
from frappe_wxwork.oauth2_logins import get_wx_corpid_secret


@frappe.whitelist(allow_guest=True)
def wechat_oauth_callback(code, po_name=None):
    """微信OAuth回调接口 - 只负责微信认证"""
    try:
        # 获取微信配置
        corpid, corpsecret = get_wx_corpid_secret()
        
        # 1. 通过code获取access_token
        token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}"
        token_response = requests.get(token_url).json()
        
        if token_response.get('errcode') != 0:
            frappe.log_error(f"WeChat token error: {token_response}")
            return {"success": False, "message": "微信认证失败"}
        
        access_token = token_response['access_token']
        
        # 2. 获取用户信息
        userinfo_url = f"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={access_token}&code={code}"
        userinfo_response = requests.get(userinfo_url).json()
        
        if userinfo_response.get('errcode') != 0:
            frappe.log_error(f"WeChat userinfo error: {userinfo_response}")
            return {"success": False, "message": "获取用户信息失败"}
        
        wechat_userid = userinfo_response.get('UserId')
        if not wechat_userid:
            return {"success": False, "message": "未获取到微信用户ID"}
        
        # 3. 返回微信用户ID，PO数据由前端另外获取
        return {
            "success": True,
            "wechat_userid": wechat_userid
        }
        
    except Exception as e:
        frappe.log_error(f"WeChat OAuth Error: {str(e)}")
        return {"success": False, "message": str(e)}